import {
	useMemo,
	useState,
	forwardRef,
	useImperativeHandle,
	useEffect,
	useContext,
} from "react";
import { Table, Card, Popover, Checkbox, Button } from "antd";
import { FunnelPlotOutlined } from "@ant-design/icons";
import { context } from "@src/store";
import "./index.scss";

interface ButtonsList {
	label: string;
	type?: any;
	method: Function;
}
interface paginationConfig {
	total?: number;
	pageSize?: number;
	pageNum?: number | string;
}
interface CommonTableProps {
	filter?: boolean;
	title?: string;
	topButtons?: ButtonsList[];
	bottomButtons?: ButtonsList[];
	columns: any[];
	dataSource: any[];
	showCheckBox?: boolean;
	rowKey: any;
	paginationConfig: paginationConfig;
	queryTableData: Function;
	disabledRules?: any[];
	summaryObj?: any;
	noHideColums?: string[];
	defaultQuery?: boolean;
}

function CommonTable(props: CommonTableProps, ref: any) {
	const {
		noHideColums = [],
		filter = true,
		title = "",
		topButtons = [],
		bottomButtons = [],
		columns = [],
		dataSource = [],
		showCheckBox = false,
		rowKey,
		paginationConfig = {},
		queryTableData = () => {},
		disabledRules = [],
		summaryObj = false,
		defaultQuery = true,
	} = props;
	let [state] = useContext(context);
	const [loading, setLoading] = useState(false);
	const [filterData, setPreFilterData] = useState({});
	const [showColumns, setShowColumns] = useState([] as string[]);
	const [selectedRowKeys, setSelectedRowKeys] = useState([] as any[]);

	useEffect(() => {
		if (!columns.length) {
			return;
		}
		let arr = columns
			.map((item) => item.dataIndex)
			.filter((item) => !noHideColums.includes(item));
		setShowColumns([...arr]);
		// eslint-disable-next-line
	}, [columns]);

	useEffect(() => {
		if (!defaultQuery) {
			return;
		}
		const AuthorizationCode = sessionStorage.getItem("AuthorizationCode");
		if (!AuthorizationCode) {
			return;
		}
		queryTableData({
			...filterData,
			pageNum: 1,
			pageSize: paginationConfig.pageSize,
		});
		// eslint-disable-next-line
	}, []);
	useImperativeHandle(ref, () => {
		return {
			selectedRowKeys,
			setLoading,
			setFilterData,
			filterData,
			showColumns,
		};
	});
	const setFilterData = (data: any) => {
		delete data.pageNum;
		delete data.pageSize;
		setPreFilterData({ ...data });
	};
	const changeSelectRows = (val: any) => {
		setSelectedRowKeys(val);
	};
	const rowSelection: any = {
		selectedRowKeys,
		onChange: changeSelectRows,
		getCheckboxProps: (record: any) => {
			let res = { disabled: false };
			if (!!disabledRules.length) {
				const originalValue = record[disabledRules[0].field];
				if (disabledRules[0].rule === "===") {
					res = {
						disabled:
							originalValue === disabledRules[0].validateRes,
					};
				}
				if (disabledRules[0].rule === "!==") {
					res = {
						disabled:
							originalValue !== disabledRules[0].validateRes,
					};
				}
			}
			return res;
		},
		fixed: "left",
	};
	const changeHeader = (val: any) => {
		let arr = [...val];
		arr = arr.filter((item) => !noHideColums.includes(item));
		if (!arr.length) {
			return;
		}
		setShowColumns(arr);
	};
	const extraNode = useMemo(() => {
		let buttons = null;
		if (!!topButtons && !!topButtons.length) {
			buttons = topButtons.map((item: any, index: number) => {
				return (
					<Button
						className="the-button"
						key={index}
						type={item.type}
						disabled={item.disabled}
						onClick={() => item.method()}
					>
						{item.label}
					</Button>
				);
			});
		}
		if (!!filter) {
			const tableOptions: any[] = columns
				.map((item) => {
					return { label: item.title, value: item.dataIndex };
				})
				.filter((item) => !!item)
				.filter((item) => {
					return !noHideColums.includes(item.value);
				});
			const filterContent = (
				<div style={{ maxWidth: "500px" }}>
					<div style={{ marginBottom: "10px" }}>
						设置表头显示的字段
					</div>
					<Checkbox.Group
						options={tableOptions}
						onChange={changeHeader}
						value={showColumns}
					></Checkbox.Group>
				</div>
			);
			return (
				<>
					{buttons}
					<Popover
						arrowPointAtCenter
						placement="topLeft"
						content={filterContent}
					>
						<FunnelPlotOutlined className="filter-setting" />
					</Popover>
				</>
			);
		}
		return buttons;
		// eslint-disable-next-line
	}, [topButtons, filter, columns, showColumns, noHideColums]);
	const bottomOperation = useMemo(() => {
		let buttons = bottomButtons.map((item, index) => {
			return (
				<Button
					style={{ marginLeft: 10 }}
					key={index}
					type={item.type}
					onClick={() => item.method()}
				>
					{item.label}
				</Button>
			);
		});
		return buttons;
	}, [bottomButtons]);
	const renderColumns = useMemo(() => {
		let arr = columns;
		arr = columns.filter(
			(item) =>
				showColumns.includes(item.dataIndex) ||
				noHideColums.includes(item.dataIndex)
		);
		return arr;
		// eslint-disable-next-line
	}, [columns, showColumns, dataSource, noHideColums]);
	const pagination: any = useMemo(() => {
		const { total = 0, pageSize = 5 } = paginationConfig;
		const page: any = paginationConfig.pageNum;
		const initPagination = {
			position: ["bottomCenter"],
			showTotal: (total: number | string) => `共${total}条数据`,
			total,
			current: page,
			showSizeChanger: false,
			pageSize,
			hideOnSinglePage: true,
			showQuickJumper: true,
			onChange: (pageNum: number) => {
				const AuthorizationCode =
					sessionStorage.getItem("AuthorizationCode");
				if (!AuthorizationCode) {
					return;
				}
				queryTableData({
					...filterData,
					pageNum: pageNum,
					pageSize: paginationConfig.pageSize,
				});
			},
		};
		return Object.assign(initPagination, paginationConfig);
	}, [paginationConfig, filterData, queryTableData]);

	const bottomStyle = useMemo(() => {
		if (!!state.isExpand) {
			return {
				width: "calc(100% - 200px)",
				left: 200,
				bottom: !!selectedRowKeys.length ? 0 : "-100px",
			};
		}
		return {
			width: "calc(100% - 80px)",
			left: 80,
			bottom: !!selectedRowKeys.length ? 0 : "-100px",
		};
	}, [state.isExpand, selectedRowKeys]);
	return (
		<>
			<Card className="common-table" title={title} extra={extraNode}>
				<Table
					bordered
					scroll={{ x: "100%" }}
					pagination={pagination}
					rowKey={rowKey}
					loading={loading}
					columns={renderColumns}
					dataSource={dataSource}
					rowSelection={showCheckBox ? rowSelection : undefined}
					summary={(pageData) => {
						if (!summaryObj) {
							return null;
						}
						let obj: any = { ...summaryObj };
						let showItems = Object.keys(obj);
						pageData.forEach((item) => {
							showItems.forEach((field) => {
								obj[field] += item[field];
							});
						});
						let List = [];
						List = showColumns;
						return (
							<Table.Summary fixed>
								<Table.Summary.Row>
									<Table.Summary.Cell
										index={0}
										align="center"
									>
										合计
									</Table.Summary.Cell>
									{List.map((item, theindex) => {
										let str = null;
										if (showItems.includes(item)) {
											str = obj[item];
										}
										return (
											<Table.Summary.Cell
												key={item}
												index={1 + theindex}
												align="center"
											>
												{str}
											</Table.Summary.Cell>
										);
									})}
								</Table.Summary.Row>
							</Table.Summary>
						);
					}}
				/>
			</Card>
			{!!bottomButtons.length && (
				<div className="common-bottom-navigation" style={bottomStyle}>
					<div>
						已选择{" "}
						<span className="the-selected-count">
							{selectedRowKeys.length}
						</span>{" "}
						项
					</div>
					<div>{bottomOperation}</div>
				</div>
			)}
		</>
	);
}

export default forwardRef(CommonTable);
